package com.example.jetpack.b_viewModel_livedata.livedata

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import androidx.lifecycle.switchMap

class UserViewModel : ViewModel() {
    /**
     * map 基本用法
     */
    private val userData = MutableLiveData<User>()

    init {
        userData.value = User(1, "Jake", "Winter", 28)
    }

    val userName: LiveData<String> = userData.map {
        "${it.firstName} ${it.lastName}"
    }

    private val userIdLiveData = MutableLiveData<Int>()

    /**
     * switchMap 基本用法
     */
    val user: LiveData<User> = userIdLiveData.switchMap { userId ->
        Repository.getUser(userId)
    }

    /**
     * 更新 userIdLiveData
     */
    fun getUser(userId: Int) {
        // 调用 setValue 方法，便认为 userIdLiveData 被更新了，
        // 无论 userIdLiveData 的值是否变化
        userIdLiveData.value = userId
    }
}